package com.student.dms;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter4.BaseQuickAdapter;
import com.chad.library.adapter4.QuickAdapterHelper;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.luck.picture.lib.utils.ToastUtils;
import com.student.db.AccountDao;
import com.student.db.AccountEntity;
import com.student.db.AppDatabase;
import com.student.db.PunchEntity;
import com.student.dms.databinding.FragmentAdminHomeBinding;
import com.student.dms.databinding.FragmentAdminManagerBinding;
import com.student.dms.databinding.FragmentStudentHomeBinding;
import com.student.dms.databinding.ItemAdminGoOutBinding;
import com.student.dms.databinding.ItemAdminStudentBinding;
import com.student.dms.databinding.ItemRecyerviewBinding;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class AdminManagerFragment extends BaseFragment<FragmentAdminManagerBinding> {

    private BaseQuickAdapter<AccountEntity, VH> baseQuickAdapter;
    private AppDatabase roomDatabase;
    private AccountDao accountDao;
    private AccountEntity accountEntity;
    private String query;
    private String username;

    @Override
    public void setViewBinding() {
        mViewBinding = FragmentAdminManagerBinding.inflate(getLayoutInflater());
    }

    @Override
    public void init() {
        SharedPreferences sharedPreferences =requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        username = sharedPreferences.getString("username", "");
        roomDatabase = DMSApplication.getApplication().getRoomDatabase();
        accountDao = roomDatabase.provideAccountDao();
        baseQuickAdapter = new BaseQuickAdapter<AccountEntity,VH>() {
            @NonNull
            @Override
            protected VH onCreateViewHolder(@NonNull Context context, @NonNull ViewGroup viewGroup, int i) {
                VH vh = new VH(ItemAdminStudentBinding.inflate(LayoutInflater.from(context), viewGroup, false));
                return vh;
            }

            @Override
            protected void onBindViewHolder(@NonNull VH vh, int position, @Nullable AccountEntity itemData) {
                vh.itemViewBidnng.name.setText("姓名："+itemData.getName());
                String sex;
                if(itemData.getSex()==1){
                    sex="男";
                }else{
                    sex="女";
                }
                vh.itemViewBidnng.sex.setText("性别："+sex);
                vh.itemViewBidnng.roomNo.setText("寝室号："+itemData.getRoomNo());
                vh.itemViewBidnng.floorNo.setText("楼栋："+itemData.getFloorNo());
                vh.itemViewBidnng.phone.setText("手机号："+itemData.getPhoneNum());
                if(accountEntity!=null && accountEntity.getType()==1){
                    vh.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //userInfo
                            Intent intent = new Intent(requireActivity(),ChangeInfoActivity.class);
                            intent.putExtra("userInfo",itemData);
                            startActivity(intent);
                        }
                    });
                }
            }
        };
        QuickAdapterHelper build = new QuickAdapterHelper.Builder(baseQuickAdapter).build();
        mViewBinding.recyclerView.setAdapter(build.getAdapter());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity());
        mViewBinding.recyclerView.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL);
        mViewBinding.recyclerView.addItemDecoration(dividerItemDecoration);

        mViewBinding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                String floorNo = AdminManagerFragment.this.accountEntity.getFloorNo();
                Log.i("searchView","onQueryTextSubmit floorNo:"+floorNo);
                AdminManagerFragment.this.query=query;
                if(!TextUtils.isEmpty(floorNo)){
                    searchAccount(query,floorNo);
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                String floorNo = AdminManagerFragment.this.accountEntity.getFloorNo();
                Log.i("searchView","onQueryTextChange floorNo:"+floorNo);
                AdminManagerFragment.this.query=newText;
                if(!TextUtils.isEmpty(floorNo)){
                    searchAccount(query,floorNo);
                }
                return false;
            }
        });
    }

    private void searchAccount(String content,String floorNo){
        disposable.add(accountDao.searchAccount(content,floorNo).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(list -> {
            //记得移除所有管理员数据，管理员不能管理管理员
            List<AccountEntity> collect = list.stream().filter(accountEntity -> {
                return accountEntity.getType() != 1;
            }).collect(Collectors.toList());
            baseQuickAdapter.submitList(collect);
        }, studentFlowThrowable -> {
            ToastUtils.showToast(requireActivity(), "用户不存在，请注册！");
        }));
    }

    @Override
    public void onResume() {
        super.onResume();
        Single<AccountEntity> accountFlow = accountDao.searchAccountByName(username);
        disposable.add(accountFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(accountEntity -> {
            this.accountEntity =accountEntity;
            Flowable<List<AccountEntity>> searchAccountFlow;
            if(!TextUtils.isEmpty(query)){
                searchAccountFlow = accountDao.searchAccount(query,AdminManagerFragment.this.accountEntity.getFloorNo());
            }else{
                searchAccountFlow=accountDao.getAccounts(AdminManagerFragment.this.accountEntity.getFloorNo());
            }
            disposable.add(searchAccountFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(list -> {
                //记得移除所有管理员数据，管理员不能管理管理员
                List<AccountEntity> collect = list.stream().filter(filter -> {
                    return filter.getType() != 1;
                }).collect(Collectors.toList());
                baseQuickAdapter.submitList(collect);
            }, studentFlowThrowable -> {
                ToastUtils.showToast(requireActivity(), "用户不存在，请注册！");
            }));
        }, studentFlowThrowable -> {
            ToastUtils.showToast(requireActivity(), "用户不存在，请注册！");
        }));

    }

    static class VH extends RecyclerView.ViewHolder {
        @NonNull
        public ItemAdminStudentBinding itemViewBidnng;
        public VH(@NonNull ItemAdminStudentBinding itemViewBidnng) {
            super(itemViewBidnng.getRoot());
            this.itemViewBidnng = itemViewBidnng;
        }
    }
}
